#include "term.h"
#include <cctype>
#include <cstdlib>

Term::Term() : coeff(0), deg(0) {}

Term::Term(int coeff)
{
    this->coeff = coeff;
    this->deg = 0;
}

Term::Term(int coeff, int deg) : coeff(coeff), deg(deg) {}

Term::Term(const std::string &str)
{
    if (std::isdigit(str[0]) || std::isdigit(str[1]))
    {
        coeff = std::stoi(str);
    }
    else
    {
        coeff = (str[0] == '-') ? -1 : 1;
    }
    deg = (str.find('^') != std::string::npos) ? std::stoi(str.substr(str.find('^') + 1)) : (str.find('x') != std::string::npos) ? 1
                                                                                                                                 : 0;
}

int Term::getCoeff() const
{
    return coeff;
}

int Term::getDeg() const
{
    return deg;
}

void Term::setCoeff(int a)
{
    coeff = a;
}

void Term::setDeg(int a)
{
    deg = a;
}

std::ostream &operator<<(std::ostream &out, const Term &t)
{
    if (t.coeff != 0)
    {
        if (t.deg == 0)
        {
            out << abs(t.coeff);
        }
        else if (t.deg == 1)
        {
            if (abs(t.coeff) != 1)
            {
                out << t.coeff;
            }
            else
            {
                if (t.coeff == -1)
                {
                    out << "-";
                }
            }
            out << "x";
        }
        else
        {
            if (abs(t.coeff) != 1)
            {
                out << t.coeff;
            }
            else
            {
                if (t.coeff == -1)
                {
                    out << "-";
                }
            }
            out << "x^" << t.deg;
        }
    }
    else
    {
        out << '0';
    }
    return out;
}

Term operator+(const Term &t1, const Term &t2)
{
    return Term(t1.coeff + t2.coeff, t1.deg);
}

std::istream &operator>>(std::istream &in, Term &t)
{
    std::string str, result;
    getline(std::cin, str);
    for (char c : str)
    {
        if (c != ' ')
        {
            result += c;
        }
    }
    t.coeff = stoi(result);
    t.deg = stoi(result.substr(result.find("^") + 1));
    return in;
}